package cn.edu.xjtu.data_structure.chapter02_stack_queue.stack;

import cn.edu.xjtu.data_structure.chapter01_linearlist.linkedlist.Link;

/**
 * @author yjq
 * @version 1.0
 * @date 2021/9/11 15:28
 */
public class LStack<T> implements StackADT<T> {
    private Link<T> top;//栈顶元素

    //初始化与构造器
    private void setUp() {
        top = null;
    }

    public LStack() {
        setUp();
    }

    public LStack(int size) {
        setUp();
    }

    @Override
    public void clear() {
        top = null;
    }

    @Override
    public void push(T it) {
        top = new Link<T>(it, top);
    }

    @Override
    public T pop() {
        if (isEmpty()) {
            System.out.println("stack is empty");
            return null;
        }
        T it = top.getElement();
        top = top.getNext();
        return it;
    }

    @Override
    public T topValue() {
        if (isEmpty()) {
            System.out.println("no top value");
            return null;
        }
        return top.getElement();
    }

    @Override
    public boolean isEmpty() {
        return top == null;
    }

    @Override
    public void print() {
        if (isEmpty()) {
            System.out.println("empty");
            return;
        }
        Link<T> temp = top;
        while (temp != null) {
            System.out.println(temp.getElement());
            temp = temp.getNext();
        }
    }

    @Override
    public int size() {
        int size=0;
        Link<T> temp = top;
        while (temp != null) {
            temp = temp.getNext();
            size++;
        }
        return size;
    }
}
